import { NextRequest, NextResponse } from 'next/server';
import { registerUser } from '@/lib/auth';
import { initDataFiles, initDefaultCategories } from '@/lib/data';
import { initAdminUser } from '@/lib/init';

export async function POST(request: NextRequest) {
  try {
    initDataFiles();
    initDefaultCategories();
    await initAdminUser();
    
    const { username, password } = await request.json();

    if (!username || !password) {
      return NextResponse.json(
        { success: false, message: '用户名和密码不能为空' },
        { status: 400 }
      );
    }

    const result = await registerUser(username, password);
    
    if (!result.success) {
      return NextResponse.json(result, { status: 400 });
    }

    return NextResponse.json(result);
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '注册失败' },
      { status: 500 }
    );
  }
}

